<?php
/**
 * 零起飞-(07FLY-CRM)
 * ==============================================
 * 版权所有 2015-2028   成都零起飞网络，并保留所有权利。
 * 网站地址: http://www.07fly.xyz
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ==============================================
 * WorkflowDiyDataor: kfrs <goodkfrs@QQ.com> 574249366
 * Date: 2019-10-3
 */

namespace app\workflow\logic;

use app\common\logic\TableField;
use think\Db;

/**
 *  自定义表单数据管理逻辑
 */
class WorkflowDiyData extends WorkflowBase
{

    private $tablefield = null;

    /**
     * 析构函数
     */
    function __construct()
    {
        $this->tablefield = new TableField();
    }

    /**
     * 封装orderby
     * @param array $data
     * Author: lingqifei created by at 2020/3/2 0002
     */
    public function getOrderby($data = [])
    {
        $order_by = '';
        //排序操作
        if (!empty($data['orderField'])) {
            $orderField = $data['orderField'];
            $orderDirection = $data['orderDirection'];
        } else {
            $orderField = "";
            $orderDirection = "";
        }
        if ($orderField == 'by_name') {
            $order_by = "name $orderDirection";
        } else {
            $order_by = "id desc";
        }
        return $order_by;
    }


    /**
     *  自定义表单数据列表
     */
    public function getWorkflowDiyDataList($data = [], $paginate = DB_LIST_ROWS)
    {
        if (empty($data['diy_form_id'])) {
            throw_response_error('选择自定义表单');
        }

        //主表信息
        $table = $this->modelWorkflowDiyForm->getInfo(['id' => $data['diy_form_id']], 'ext_table,main_table');
        $condition['ext_table'] = $table['ext_table'];
        $condition['main_table'] = $table['main_table'];
        $fields = $this->modelWorkflowDiyField->getList($condition, '*', '', false);

        //扩展数据处理
        $where['diy_form_id'] = ['=', $data['diy_form_id']];

        if (!empty($data['listtype']) && $data['listtype']=='myself') {
            $where['create_user_id'] = ['=', SYS_USER_ID];
        }

        if (!empty($data['bdate'])) {
            $where['create_time'] = ['>=', strtotime($data['bdate'])];
        }

        if (!empty($data['edate'])) {
            $where['create_time'] = ['<', strtotime($data['edate'])];
        }

        if (!empty($data['bdate']) && !empty($data['edate'])) {
            $date_range = [strtotime($data['bdate']), strtotime($data['edate'])];
            $where['create_time'] = ['between', $date_range];
        }


        $list = Db::name(SYS_DB_PREFIX . $table['ext_table'])
            ->where($where)
            ->order('create_time desc')
            ->paginate($paginate)
            ->ToArray();
        foreach ($list['data'] as &$row) {
            $row['audit_status_arr'] = $this->modelWorkflowDiyData->audit_status($row['audit_status']);
        }
        return $list;
    }

    /**
     *  自定义表单数据列表
     */
    public function getWorkflowDiyDataCount($data = [], $paginate = DB_LIST_ROWS)
    {
        if (empty($data['diy_form_id'])) {
            throw_response_error('选择自定义表单');
        }

        //主表信息
        $table = $this->modelWorkflowDiyForm->getInfo(['id' => $data['diy_form_id']], 'ext_table,main_table');

        //扩展数据处理
        $where['diy_form_id'] = ['=', $data['diy_form_id']];

        if (!empty($data['create_user_id'])) {
            $where['create_user_id'] = ['=', $data['create_user_id']];
        }

        if (!empty($data['start_date'])) {
            $where['create_time'] = ['>=', strtotime($data['start_date'])];
        }

        if (!empty($data['edate'])) {
            $where['create_time'] = ['<', strtotime($data['edate'])];
        }

        if (!empty($data['bdate']) && !empty($data['edate'])) {
            $date_range = [strtotime($data['bdate']), strtotime($data['edate'])];
            $where['create_time'] = ['between', $date_range];
        }

        $count = Db::name(SYS_DB_PREFIX . $table['ext_table'])
            ->where($where)
            ->count();

        return $count;
    }


    /**
     * 自定义表单数据=》添加
     * @param array $data
     * @return array
     */
    public function workflowDiyDataAdd($data = [])
    {
        //1、查询自定义表单
        $table = $this->logicWorkflowDiyForm->getWorkflowDiyFormInfo(['id' => $data['diy_form_id']]);
        //2、检查扩展字段，是否必填写
        $this->logicWorkflowDiyField->chkFieldExtRequire($table['ext_table'], $data);

        $adddata = $data;
        $adddata['create_user_id'] = !empty($data['create_user_id']) ? $data['create_user_id'] : SYS_USER_ID;
        $adddata['owner_user_id'] = !empty($data['owner_user_id']) ? $data['owner_user_id'] : SYS_USER_ID;
        $adddata['create_time'] = time();
        $adddata['update_time'] = time();

        $result = Db::name($table['ext_table'])->insert($adddata);
        $url = url('show');
        $result && action_log('新增', '新增表单 ' . $table['ext_table'] . ' 数据：');
        return $result ? [RESULT_SUCCESS, '添加成功', $url] : [RESULT_ERROR, $this->modelWorkflowDiyData->getError()];
    }

    /**
     * 自定义表单数据=》编辑
     * @param array $data
     * @return array
     */
    public function workflowDiyDataEdit($data = [])
    {

        //1、查询自定义表单
        $table = $this->logicWorkflowDiyForm->getWorkflowDiyFormInfo(['id' => $data['diy_form_id']]);

        //2、检查扩展字段，是否必填写
        $this->logicWorkflowDiyField->chkFieldExtRequire($table['ext_table'], $data);

        //3、更新数据
        $uptData = $data;
        $uptData['update_time'] = time();
        $result = Db::name($table['ext_table'])->update($uptData);

        $url = url('show');
        $result && action_log('新增', '新增表单 ' . $table['ext_table'] . ' 数据：');
        return $result ? [RESULT_SUCCESS, '添加成功', $url] : [RESULT_ERROR, $this->modelWorkflowDiyData->getError()];
    }

    /**
     *  自定义表单数据=》删除
     */
    public function workflowDiyDataDel($data = [])
    {
        $table = $this->modelWorkflowDiyForm->getInfo(['id' => $data['diy_form_id']], 'ext_table,main_table');
        $where['diy_form_id'] = ['=', $data['diy_form_id']];
        $where['id'] = ['in', $data['id']];
        $result = Db::name($table['ext_table'])->where($where)->delete();
        $result && action_log('删除', '删除 自定义表单，where：' . http_build_query($data));
        return $result ? [RESULT_SUCCESS, ' 删除成功'] : [RESULT_ERROR, $this->modelWorkflowDiyData->getError()];
    }

    /**
     *  自定义表单数据=>信息
     */
    public function getWorkflowDiyDataInfo($data = [])
    {
        if (empty($data['diy_form_id']) || empty($data['id'])) {
            return [RESULT_ERROR, '选择表单form_id,数据id'];
        }
        $table = $this->modelWorkflowDiyForm->getInfo(['id' => $data['diy_form_id']], 'ext_table,main_table');
        $where['diy_form_id'] = ['=', $data['diy_form_id']];
        $where['id'] = ['=', $data['id']];
        $info = Db::table(SYS_DB_PREFIX . $table['ext_table'])
            ->where($where)
            ->find();
        $info['ext_table'] = $table['ext_table'];
        $info['create_user_name'] = $this->modelSysUser->getValue(['id'=>$info['create_user_id']],'realname');
        return $info;
    }

    /**
     * 自定义表单数据=》审核提交
     * @param array $data
     * @return array
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/9/18 0018
     */
    public function setWorkflowDiyDataAuditSend($data = [])
    {
        if (empty($data['diy_form_id']) || empty($data['id']) || empty($data['workflow_id'])) {
            return [RESULT_ERROR, '选择表单form_id,数据id,审批模板workflow_id'];
        }

        //获得审核的信息
        $info = $this->getWorkflowDiyDataInfo($data);

        //把表单数据送到审批中去
        $interfaceData['business_type'] = $info['ext_table'];
        $interfaceData['business_id'] = $data['id'];
        $intedata['apply_user_id'] = $info['create_user_id'];//业务申请人员=业务表单的归属人员、负责人员
        $intedata['create_user_id'] = SYS_USER_ID;//创建人员

        $res = $this->logicWorkflowBusiness->workflowAddInterface($interfaceData);

        if ($res[0] == RESULT_ERROR) return $res;

        $where['id'] = $info['id'];
        $uptData['audit_status'] = 2;
        $result = Db::name($info['ext_table'])->where($where)->update($uptData);

        $result && action_log('提交', '自定义表单数据送审核：' . $info['ext_table'] . $info['id']);
        return $result ? [RESULT_SUCCESS, '操作成功', ''] : [RESULT_ERROR, $this->modelOaBorrow->getError()];
    }

    /**
     * 自定义表单数据=》取消审批状态
     * @param array $data
     * @return array
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/9/18 0018
     */
    public function setWorkflowDiyDataAuditCancel($data = [])
    {
        if (empty($data['diy_form_id']) || empty($data['id'])) {
            return [RESULT_ERROR, '选择表单form_id,数据id'];
        }
        //获得审核的信息
        $info = $this->getWorkflowDiyDataInfo($data);
        $where['id'] = $info['id'];
        $uptData['audit_status'] = 5;//撤消
        $result = Db::name($info['ext_table'])->where($where)->update($uptData);
        $result && action_log('撤消', '取消借款审核：' . $data['id']);
        return $result ? [RESULT_SUCCESS, '操作成功', ''] : [RESULT_ERROR, $this->modelOaBorrow->getError()];
    }

}
